package org.example.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.java.Log;
import org.example.bean.Product;
import org.example.bean.User;
import org.example.configs.OssConfig;
import org.example.dao.ProductMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.UUID;

@Service
@AllArgsConstructor
@Log
public class ProductServiceImpl implements ProductService {
    private final ProductMapper productMapper;
    private final OssConfig ossConfig;
    private final OSS ossClient;

    @Override
    @Transactional
    public Product addProduct(Product product) {


        //第一步上传图片到Oss
        //主图
        MultipartFile MainImgFile=product.getMainImgFile();
        String mainImageUrl = addImg(MainImgFile);
        product.setMain_url(mainImageUrl);

        //子图
        MultipartFile[] subImgFile = product.getSubImgFile();
        StringBuffer sb=new StringBuffer();
        for (MultipartFile subImg : subImgFile) {
            String subImageUrl = addImg(subImg);
            sb.append(subImageUrl).append(", ");
        }
        product.setSub_url(sb.toString());

        productMapper.insert(product);
        return product;
    }


    //添加商品图片
    public String addImg(MultipartFile imgFile){
        String originalFilename = imgFile.getOriginalFilename();//文件名
        String fileExtension="";//文件扩展名
        if(originalFilename.contains(".")&&originalFilename!=null){
            fileExtension=originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        System.out.println("原文件名："+originalFilename+"\t扩展名"+fileExtension);
        String objectKey="files/"+ UUID.randomUUID().toString()+fileExtension; //保存的对象在oss中的地址
        PutObjectRequest putObjectRequest=null;
        try {
            putObjectRequest = new PutObjectRequest(ossConfig.getBucketName(), objectKey, imgFile.getInputStream());
            ossClient.putObject(putObjectRequest);   //上传到Oss

            String fileUrl = ossConfig.getUrlPrefix() + File.separator + objectKey;
            return fileUrl;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("上传文件到OSS失败"+ e.getMessage());
            throw new RuntimeException("上传文件到OSS失败"+e.getMessage());
        }
    }

    //查询特价商品
    @Override
    public List<Product> getSpecialProducts(Integer product_status) {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        if (product_status!=null){
            wrapper.eq(Product::getProduct_status,product_status);
        }
        wrapper.apply("price < original_price");
        return productMapper.selectList(wrapper);
    }

    //根据状态查询产品,逆序输出
    @Override
    public List<Product> getAllProducts(Integer product_status) {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        if (product_status!=null && product_status!=-1){
            wrapper.eq(Product::getProduct_status,product_status);
        }
        return productMapper.selectList(wrapper);
    }

    @Override
    public Product getProductById(Integer product_id) {
        return productMapper.selectById(product_id);
    }

    @Override
    public List<Product> getProductsByCategoryId(Integer category_id) {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getCategory_id,category_id);
        return productMapper.selectList(wrapper);
    }

    @Override
    @Transactional
    public boolean updateProductStatus(Integer product_id, Integer product_status) {
        Product product = productMapper.selectById(product_id);
        product.setProduct_status(product_status);
        return productMapper.updateById(product)>0;
    }

    @Override
    @Transactional
    public boolean updateProduct(Integer product_id, Product product) {
        Product oldProduct = this.productMapper.selectById(product_id);
        if(oldProduct==null){
            throw new RuntimeException("用户不存在"+product_id);
        }
        oldProduct.setProduct_name(product.getProduct_name());
        oldProduct.setCategory_id(product.getCategory_id());
        oldProduct.setDescription(product.getDescription());
        oldProduct.setPrice(product.getPrice());
        oldProduct.setOriginal_price(product.getOriginal_price());
        //第一步上传图片到Oss
        //主图
        MultipartFile MainImgFile=product.getMainImgFile();
        String mainImageUrl = addImg(MainImgFile);
        oldProduct.setMain_url(mainImageUrl);

        //子图
        MultipartFile[] subImgFile = product.getSubImgFile();
        StringBuffer sb=new StringBuffer();
        for (MultipartFile subImg : subImgFile) {
            String subImageUrl = addImg(subImg);
            sb.append(subImageUrl).append(", ");
        }
        oldProduct.setSub_url(sb.toString());
        return productMapper.updateById(oldProduct)>0;
    }

    @Override
    public Product getProductDetailById(Integer product_id) {
        return productMapper.selectProductById(product_id);
    }
}
